<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>目录授权</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<style>
    .messageRecipients i{
        font-style: normal;
    }
    .messageRecipients i.layui-icon-close{
        cursor: pointer;
    }
    .messageRecipients{
        display: inline-block;
        line-height: 12px;
        padding: 5px 10px;
        margin-right: 5px;
        background: rgba(8,157,213,0.3);
        border: 1px solid #0b73df;
    }
    .layui-table td,.layui-table th{text-align: center;}
    .layui-textarea{
        min-height: 60px;
        width: 220px;
    }
    form.layui-form{
        height: 100%
    }
    .privateSubmit{
        margin: 0 10px;
    }
    .layui-table th,.layui-table td{
        padding: 5px 0;
    }
    .privateSubmitDiv{
        position: absolute;
        bottom: 0px;
        width: 100%;
        text-align: center;
        background: #fff;
        padding: 10px 0;
    }
</style>
<body>
<form class="layui-form">
    <div class="privateSubmitDiv">
        <button class="layui-btn btn-n privateSubmit" lay-submit lay-filter="privateSubmit">提交</button>
    </div>

    <div style="padding: 0 10px;">
        <table class="layui-table">
            <thead>
            <tr>
                <th style="font-weight: bold;">名称</th>
                <th>权限</th>
            </tr>
            </thead>
            <tbody class="layui-form tableBody" lay-filter="tableBody">
            <tr>
                <td class="slNames" name=""></td>
                <td>
                    <div class="layui-inline">
                        <div class="layui-input-inline">
                            <select name="permissionType" lay-filter="permissionType">
                                <option value="">请选择</option>
                                <option value="none">无</option>
                                <option value="everyone">所有人</option>
                                <option value="user">用户</option>
                                <option value="role">角色</option>
                                <option value="org">组织</option>
                            </select>
                        </div>
                        <textarea style="display: none;" name="cmpIds" class="hiddenJson"></textarea>
                        <div style="display: inline-block;vertical-align: middle;max-width: 400px;min-width: 200px;width: auto"  class="textarea layui-textarea" readonly="readonly"></div>
                        <a class="windowButton layui-btn layui-btn-sm" ><span>选择...</span></a>
                        <span class="font" style='vertical-align: middle;color: #a9302a;'>必填</span>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</form>
<script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','common','laydate','jquery','commons','form','layer','setter'], function () {
        var laydate = layui.laydate;
        var $ = layui.jquery;
        var commons = layui.commons;
        var form = layui.form;
        var layer = layui.layer;
        var setter = layui.setter;
        $(".windowButton,.textarea,.font").hide();
        var dateTimeFiledLen = $(".dateTimeFiled");
        for(var i=0;i<dateTimeFiledLen.length;i++){
            laydate.render({
                elem: dateTimeFiledLen[i] //指定元素
                ,type: 'date'
                ,trigger: 'click'
            });
        }
        function displayMessage (){
            $('.tableBody tr').eq(i).children('td').eq(0).text(parentName).attr('name',parentId);
            $('.tableBody tr').eq(i).find("select[name='permissionType']").val(typeVal);
        }
        //权限信息回显
        var manageField = '${manageField}';
        var parentName = ' ${parentName}';
        var parentId = '  ${parentId}';
        var parType='${parType}';
        if (manageField == "") { //如果没有设置过按钮权限，默认是所有人都不能看到
            $('.tableBody tr').eq(0).children('td').eq(0).text(parentName).attr('name',parentId)
            $("select[name='permissionType']").find("option[value='none']").attr("selected", true);
        } else {
            var arr = JSON.parse(manageField);
            for (i = 0; i < arr.length; i++) {
                var desc = arr[i].desc;
                var name = arr[i].name;
                var showNames = arr[i].right[0].names;
                var showIds = arr[i].right[0].ids;
                var typeVal = arr[i].right[0].type;
                if (parentId==-1){
                    if (typeVal !=='none'&&typeVal !== 'everyone'){
                        displayMessage();
                        $('.tableBody tr').eq(i).find(".windowButton").show();
                        $.each(showNames.split(","),function (index, item) {
                            var htmls = '<span class="messageRecipients"><i>'+item.replace(/&/g,"'")+'</i><i value='+showIds.split(',')[index]+' class="layui-icon layui-icon-close"></i></span>'
                            $('.tableBody tr').eq(i).find(".textarea").show().append(htmls)
                        });
                    }else {
                        displayMessage();
                    }
                }else {
                    if (parType !=='none'&&parType !== 'everyone'){
                        displayMessage();
                        $('.tableBody tr').eq(i).find("select[name='permissionType']").attr("disabled","disabled")
                        $.each(showNames.split(","),function (index, item) {
                            var htmls = '<span class="messageRecipients"><i>'+item.replace(/&/g,"'")+'</i><i value='+showIds.split(',')[index]+' class="layui-icon layui-icon-close"></i></span>'
                            $('.tableBody tr').eq(i).find(".textarea").show().append(htmls)
                        });
                    }else if (parType=='everyone'){
                        if (typeVal !=='none'&&typeVal !== 'everyone'){
                            displayMessage();
                            $('.tableBody tr').eq(i).find(".windowButton").show();
                            $.each(showNames.split(","),function (index, item) {
                                var htmls = '<span class="messageRecipients"><i>'+item.replace(/&/g,"'")+'</i><i value='+showIds.split(',')[index]+' class="layui-icon layui-icon-close"></i></span>'
                                $('.tableBody tr').eq(i).find(".textarea").show().append(htmls)
                            });
                        }else {
                            displayMessage();
                        }
                    }else {
                        if (typeVal !=='none'&&typeVal !== 'everyone'){
                            displayMessage();
                            $('.tableBody tr').eq(i).find("select[name='permissionType']").attr("disabled","disabled")
                            $.each(showNames.split(","),function (index, item) {
                                var htmls = '<span class="messageRecipients"><i>'+item.replace(/&/g,"'")+'</i><i value='+showIds.split(',')[index]+' class="layui-icon layui-icon-close"></i></span>'
                                $('.tableBody tr').eq(i).find(".textarea").show().append(htmls)
                            });
                        }else {
                            displayMessage();
                        }
                    }
                }
            }
            deledeMessage();
            form.render();
        }
        form.on('submit(privateSubmit)', function(data){
            var flag = true;
            var dataAll = [];

            if ($('.tableBody tr').eq(0).find("select[name='permissionType']").val()==''){
                $('.tableBody tr').eq(0).find(".font").show();
                flag = false;
            }else {
                var data = {
                    desc:$('.tableBody tr').eq(0).children(".slNames").text(),
                    name:JSON.parse(localStorage.getItem('nowTreeNodeinfos')).Id,
                    right:[]
                };
                var rigData = {};
                if ($('.tableBody tr').eq(0).find("select[name='permissionType']").val()!=='none'&& $('.tableBody tr').eq(0).find("select[name='permissionType']").val()!=='everyone'){
                    rigData.type = $('.tableBody tr').eq(0).find("select[name='permissionType']").val();
                    if ($('.tableBody tr').eq(0).find(".textarea").text() == "") {
                        layer.msg('请选择对应维度下的数据！', {icon: 0});
                        flag = false;
                    }
                    var rigDatanames='';
                    var rigDataids='';
                    $.each($('.textarea').children("span"),function (k,v) {
                        rigDatanames += $(v).find("i").eq(0).html().replace(/\"/g,"&")+',';
                        rigDataids += $(v).find("i").eq(1).attr("value")+',';
                    })
                    rigData.names = rigDatanames.substring(0,rigDatanames.length-1);
                    rigData.ids = rigDataids.substring(0,rigDataids.length-1);
                }else {
                    rigData.type = $('.tableBody tr').eq(0).find("select[name='permissionType']").val();
                }
                data.right.push(rigData);
                dataAll.push(data)
            }
            var nodeId = '${nodeId}'
            var params = {nodeId: nodeId, permissionType: 2, manageField: JSON.stringify(dataAll)};
            if (flag){
                $.ajax({
                    url: serverPath.systemPath + setter.sysLinkPath + "fileManagementPermission/permissionSave",
                    type: "post",
                    dataType: 'json',
                    data: params,
                    success: function (data) {
                        if (data.code==0){
                            var index=parent.layer.getFrameIndex(window.name);//获取当前弹出层的层级
                            parent.layer.close(index);//关闭弹出层
                            parent.layer.msg('保存成功！', {icon: 6});
                        }else {
                            layer.msg('保存失败！', {icon: 5});
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                    }
                })
            }

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        form.on('select(permissionType)', function(data){
            if(data.value!==''){
                $(data.othis).parent().siblings(".font").hide();
                if (data.value!=='none'&&data.value!=='everyone'){
                    $(data.othis).parent().siblings(".windowButton").show();
                    $(data.othis).parent().siblings(".textarea").show().text('');
                }else {
                    $(data.othis).parent().siblings(".windowButton,.textarea").hide();
                    $(data.othis).parent().siblings(".textarea").hide().text('');
                }
            }else {
                $(data.othis).parent().siblings(".windowButton,.textarea").hide();
                $(data.othis).parent().siblings(".textarea").hide().text('');
            }

        });
        function deledeMessage() {
            $('.messageRecipients i.layui-icon-close').click(function () {
                var conditionId = $(this).attr('value'),
                    thet = $(this)
                layer.confirm('确定删除吗？',{title:'提示'}, function(index) {
                    thet.parent().remove();
                    layer.close(index);
                    layer.msg('删除成功',{icon:1})
                });
            })
        }
        $(document).off('click','.windowButton').on('click', '.windowButton', function () {
            var userSelectorWin;
            var body;
            var itemName='';
            var itemId='';
            var theData = $(this).siblings(".textarea");
            var hiddenData = $(this).siblings(".hiddenJson");
            //获取当前行的选中值
            var val= $(this).parent().find('select[name=permissionType]').val();
            switch (val) {
                case 'user':
                    parent.layer.open({
                        type:2
                        ,title:'人员选择器'
                        ,area:['980px','630px']
                        ,btn:["保存","取消","撤销"]
                        ,resize:false
                        ,content: serverPath.systemPath + setter.sysLinkPath+'dialog/view/sysUserDialog'
                        ,success: function(layero, index){
                            body = parent.layer.getChildFrame('body',index);
                            userSelectorWin = parent.window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            //向用户选择器页面传递初始值[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                            if (theData.text()) {
                                userSelectorWin.layui.userList = [];
                                $.each(theData.children('span'),function (k,v) {
                                    var userListObj={};
                                    userListObj.name = $(v).find("i").eq(0).text();
                                    userListObj.userId = $(v).find("i").eq(1).attr("value");
                                    userSelectorWin.layui.userList.push(userListObj);
                                })
                            }
                        }
                        ,yes:function(index,layero){
                            var theUserList = body.find("input[name=userList]").val();
                            if (theUserList&&theUserList!=="[]"){
                                theData.html("");
                                //用户选择器返回的选择人员数组[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                                $.each(JSON.parse(theUserList),function (index, item) {
                                    var htmls = '<span class="messageRecipients"><i>'+item.name+'</i><i value='+item.userId+' class="layui-icon layui-icon-close"></i></span>'
                                    theData.append(htmls)
                                });
                                deledeMessage();
                            }else{
                                theData.html("");
                            }
                            parent.layer.close(index);
                        },
                        btn3:function(index, layero){
                            userSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                    break;
                case 'role':
                    parent.layer.open({
                        type: 2
                        , title: '角色选择器'
                        , area: ['980px', '630px']
                        ,btn:["保存","取消","撤销"]
                        , resize: false
                        , content:serverPath.systemPath + setter.sysLinkPath +'dialog/view/sysRoleDialog'
                        ,success: function(layero, index){
                            body = parent.layer.getChildFrame('body',index);
                            userSelectorWin = parent.window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            //向用户选择器页面传递初始值[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                            // userSelectorWin.layui.userList.push({name:"wc",userId:"ec17d71488dd43f3ac8ea1a01971d7cc"});
                            if (theData.text()) {
                                userSelectorWin.layui.roleList = [];
                                $.each(theData.children('span'),function (k,v) {
                                    var userListObj={};
                                    userListObj.name = $(v).find("i").eq(0).text();
                                    userListObj.roleId = $(v).find("i").eq(1).attr("value");
                                    userSelectorWin.layui.roleList.push(userListObj);
                                })
                            }
                        }
                        ,yes:function(index,layero){
                            var roleList = body.find("input[name=roleList]").val();
                            if (roleList&&roleList!=="[]"){
                                theData.html("");
                                $.each(JSON.parse(roleList),function (index, item) {
                                    var htmls = '<span class="messageRecipients"><i>'+item.name+'</i><i value='+item.roleId+' class="layui-icon layui-icon-close"></i></span>'
                                    theData.append(htmls)
                                });
                                deledeMessage();
                            }else{
                                theData.html("");
                            }
                            parent.layer.close(index);
                        },
                        btn3:function(index, layero){
                            userSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                    break;
                case 'org':
                    parent.layer.open({
                        type: 2
                        , title: '组织选择器'
                        , area: ['980px', '630px']
                        ,btn:["保存","取消","撤销"]
                        , resize: false
                        , content: serverPath.systemPath + setter.sysLinkPath+ 'dialog/view/sysOrgDialog'
                        ,success: function(layero, index){
                            body = parent.layer.getChildFrame('body',index);
                            userSelectorWin = parent.window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            //向用户选择器页面传递初始值[{name:"name1",userId:"userId1"},{name:"name2",userId:"userId2"}...]
                            if (theData.text()) {
                                userSelectorWin.layui.orgList = [];
                                $.each(theData.children('span'),function (k,v) {
                                    var userListObj={};
                                    userListObj.name = $(v).find("i").eq(0).html().replace(/\"/g,"'");
                                    userListObj.orgId = $(v).find("i").eq(1).attr("value");
                                    userSelectorWin.layui.orgList.push(userListObj);
                                })
                            }
                        }
                        ,yes: function(index, layero){
                            var theUserList = body.find("input[name=orgList]").val();
                            if (theUserList&&theUserList!=="[]"){
                                theData.html("");
                                $.each(JSON.parse(theUserList),function (index, item) {
                                    var htmls = '<span class="messageRecipients"><i>'+item.name+'</i><i value='+item.orgId+' class="layui-icon layui-icon-close"></i></span>'
                                    theData.append(htmls)
                                });
                                deledeMessage();
                            }else {
                                theData.html("");
                            }
                            parent.layer.close(index);
                        },
                        btn3:function(index, layero){
                            userSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                    break;
            };
        });
    });
</script>
</body>
</html>